package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.ParamBean;
import com.shjn.squirrel.bean.httpBean.RecordBean;
import com.shjn.squirrel.bean.httpBean.SaveRecyclingRecordReq;
import com.shjn.squirrel.bean.storageBean.WastePrice;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.RecyclerInfoCache;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.OrderUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 回收员垃圾选择
 */
public class RecyclerSelectFragment extends BaseFragment implements View.OnClickListener {

    private static RecyclerSelectFragment instance;
    //垃圾选择按钮
    private ImageButton mBtnBottle;
    private ImageButton mBtnPaper;
    private ImageButton mBtnBook;
    private ImageButton mBtnPlastic;
    private ImageButton mBtnFabric;
    private ImageButton mBtnMetal;
    private ImageButton mBtnGlass;
    private ImageButton mBtnHarm;
    //垃圾价格
    private TextView mBottlePrice;
    private TextView mPaperPrice;
    private TextView mBookPrice;
    private TextView mPlasticPrice;
    private TextView mFabricPrice;
    private TextView mMetalPrice;
    private ArrayList<WastePrice> mWastePrice;
    //满箱状态
    private TextView mFullWarningBottle;
    private TextView mFullWarningBook;
    private TextView mFullWarningPaper;
    private TextView mFullWarningPlastic;
    private TextView mFullWarningFabric;
    private TextView mFullWarningMetal;
    private TextView mFullWarningGlass;
    private TextView mFullWarningHarm;
    private TextView[] mFullWarings;
    //垃圾重量或数量
    private TextView mBottleCount;
    private TextView mPaperWeight;
    private TextView mBookWeight;
    private TextView mPlasticWeight;
    private TextView mFabricWeight;
    private TextView mMetalWeight;
    private TextView mGlassWeight;
    private TextView mHarmWeight;
    private TextView[] mWeightOrCounts;

    public RecyclerSelectFragment() {
    }

    public synchronized static RecyclerSelectFragment getInstance() {
        if (instance == null) {
            instance = new RecyclerSelectFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.recycler_select_garbage, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        mActivity.mBackAndTimer.setOnBackListener(new BackAndTimerView.OnBackListener() {
            @Override
            public void onBack() {
                //退出登录，返回首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    recyclerLogout();
                }
            }
        }).setBackVisibleState(true).setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
            @Override
            public void onTimerFinish() {
                //退出登录，返回首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    recyclerLogout();
                }
            }
        }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mBtnBottle = (ImageButton) mView.findViewById(R.id.imBtn_bottle);
        mBtnPaper = (ImageButton) mView.findViewById(R.id.imBtn_paper);
        mBtnBook = (ImageButton) mView.findViewById(R.id.imBtn_book);
        mBtnPlastic = (ImageButton) mView.findViewById(R.id.imBtn_plastic);
        mBtnFabric = (ImageButton) mView.findViewById(R.id.imBtn_fabric);
        mBtnMetal = (ImageButton) mView.findViewById(R.id.imBtn_metal);
        mBtnGlass = (ImageButton) mView.findViewById(R.id.imBtn_glass);
        mBtnHarm = (ImageButton) mView.findViewById(R.id.imBtn_harm);
        mBottlePrice = (TextView) mView.findViewById(R.id.tv_bottle_price);
        mPaperPrice = (TextView) mView.findViewById(R.id.tv_paper_price);
        mBookPrice = (TextView) mView.findViewById(R.id.tv_book_price);
        mPlasticPrice = (TextView) mView.findViewById(R.id.tv_plastic_price);
        mFabricPrice = (TextView) mView.findViewById(R.id.tv_fabric_price);
        mMetalPrice = (TextView) mView.findViewById(R.id.tv_metal_price);
        mFullWarningBottle = (TextView) mView.findViewById(R.id.full_warning_bottle);
        mFullWarningPaper = (TextView) mView.findViewById(R.id.full_warning_paper);
        mFullWarningBook = (TextView) mView.findViewById(R.id.full_warning_book);
        mFullWarningPlastic = (TextView) mView.findViewById(R.id.full_warning_plastic);
        mFullWarningFabric = (TextView) mView.findViewById(R.id.full_warning_fabric);
        mFullWarningMetal = (TextView) mView.findViewById(R.id.full_warning_metal);
        mFullWarningGlass = (TextView) mView.findViewById(R.id.full_warning_glass);
        mFullWarningHarm = (TextView) mView.findViewById(R.id.full_warning_harm);
        mFullWarings = new TextView[]{mFullWarningBottle, mFullWarningPaper, mFullWarningBook, mFullWarningPlastic,
                mFullWarningFabric, mFullWarningMetal, mFullWarningGlass, mFullWarningHarm};
        mBottleCount = (TextView) mView.findViewById(R.id.tv_bottle_count);
        mPaperWeight = (TextView) mView.findViewById(R.id.tv_paper_weight);
        mBookWeight = (TextView) mView.findViewById(R.id.tv_book_weight);
        mPlasticWeight = (TextView) mView.findViewById(R.id.tv_plastic_weight);
        mFabricWeight = (TextView) mView.findViewById(R.id.tv_fabric_weight);
        mMetalWeight = (TextView) mView.findViewById(R.id.tv_metal_weight);
        mGlassWeight = (TextView) mView.findViewById(R.id.tv_glass_weight);
        mHarmWeight = (TextView) mView.findViewById(R.id.tv_harm_weight);
        mWeightOrCounts = new TextView[]{mBottleCount, mPaperWeight, mBookWeight, mPlasticWeight,
                mFabricWeight, mMetalWeight, mGlassWeight, mHarmWeight};
        mBtnBottle.setOnClickListener(this);
        mBtnPaper.setOnClickListener(this);
        mBtnBook.setOnClickListener(this);
        mBtnPlastic.setOnClickListener(this);
        mBtnFabric.setOnClickListener(this);
        mBtnMetal.setOnClickListener(this);
        mBtnGlass.setOnClickListener(this);
        mBtnHarm.setOnClickListener(this);
        //设置垃圾价格
        mWastePrice = LocalStorage.getWastePrice(MyApplication.getInstance());
        mBottlePrice.setText(String.format("%.2f", mWastePrice.get(0).getCollectorPrice()) + "元/个");
        mPaperPrice.setText(String.format("%.2f", mWastePrice.get(1).getCollectorPrice()) + "元/公斤");
        mBookPrice.setText(String.format("%.2f", mWastePrice.get(2).getCollectorPrice()) + "元/公斤");
        mPlasticPrice.setText(String.format("%.2f", mWastePrice.get(3).getCollectorPrice()) + "元/公斤");
        mFabricPrice.setText(String.format("%.2f", mWastePrice.get(4).getCollectorPrice()) + "元/公斤");
        mMetalPrice.setText(String.format("%.2f", mWastePrice.get(5).getCollectorPrice()) + "元/公斤");
        //设置垃圾分类桶状态
        if (RecyclerInfoCache.firstSelect) {
            EventBus.getDefault().register(this);
//            mActivity.serialPortUtils.sendSerialPort("androidC56:1;");//发起分类桶状态上报
            RecyclerInfoCache.firstSelect = false;
        } else {
            //设置满箱状态与垃圾量
            setCanState(RecyclerInfoCache.canState);
        }

    }

    /**
     * 分类桶状态上报通知
     *
     * @param canState
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ArrayList<ParamBean> canState) {
        //保存当前分类桶状态
        RecyclerInfoCache.canState = canState;
        //设置满箱状态与垃圾量
        setCanState(canState);
        //注销EnventBus
        EventBus.getDefault().unregister(this);
    }

    /**
     * 设置满箱状态与垃圾量
     *
     * @param canState
     */
    private void setCanState(ArrayList<ParamBean> canState) {
        for (int i = 0; i < 8; i++) {
            int canFullStatus;
            if (i == 0) {//饮料瓶
                canFullStatus = LocalStorage.getBottleState(MyApplication.getInstance()).getCanFullStatus();
                mWeightOrCounts[i].setText("当前" + LocalStorage.getBottleState(MyApplication.getInstance()).getCount() + "个");
            } else {
                canFullStatus = canState.get(i).getCanFullStatus();
                mWeightOrCounts[i].setText("当前" + String.format("%.2f", canState.get(i).getWeight()) + "公斤");
            }
            if (canFullStatus == 0) {//未满箱
                mFullWarings[i].setVisibility(View.INVISIBLE);
            } else if (canFullStatus == 1) {//80%满箱
                mFullWarings[i].setText("80%");
                mFullWarings[i].setBackgroundResource(R.drawable.full_warning_80);
                mFullWarings[i].setVisibility(View.VISIBLE);
            } else if (canFullStatus == 2) {//满箱
                mFullWarings[i].setText("暂满");
                mFullWarings[i].setBackgroundResource(R.drawable.full_warning);
                mFullWarings[i].setVisibility(View.VISIBLE);
            }

        }
    }

    /**
     * 选择垃圾种类
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        if (!RecyclerPayFragment.getInstance().isAdded() && !RecyclerFreeFragment.getInstance().isAdded()) {
            mActivity.mBackAndTimer.stop();
            //设置垃圾种类
            switch (view.getId()) {
                case R.id.imBtn_bottle:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.bottle);
                    break;
                case R.id.imBtn_paper:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.paper);
                    break;
                case R.id.imBtn_book:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.book);
                    break;
                case R.id.imBtn_plastic:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.plastic);
                    break;
                case R.id.imBtn_fabric:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.fabric);
                    break;
                case R.id.imBtn_metal:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.metal);
                    break;
                case R.id.imBtn_glass:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.glass);
                    break;
                case R.id.imBtn_harm:
                    RecyclerInfoCache.garbageParam.setCategory(Constant.harm);
                    break;
                default:
                    break;
            }
            //设置满箱参数
            int canFullStatus;
            if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
                canFullStatus = LocalStorage.getBottleState(MyApplication.getInstance()).getCanFullStatus();
            } else {
                canFullStatus = RecyclerInfoCache.canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).getCanFullStatus();
            }
            if (canFullStatus == 2) {
                RecyclerInfoCache.garbageParam.setFullState(Constant.full);
            } else if (canFullStatus == 1) {
                RecyclerInfoCache.garbageParam.setFullState(Constant.full_80);
            } else {
                RecyclerInfoCache.garbageParam.setFullState(Constant.full_no);
            }
            //设置垃圾量参数
            if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
                RecyclerInfoCache.garbageParam.setQuantity(LocalStorage.getBottleState(MyApplication.getInstance()).getCount());
            } else {
                RecyclerInfoCache.garbageParam.setQuantity(RecyclerInfoCache.canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).getWeight());
            }
            //设置垃圾金额参数
            if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.glass) || RecyclerInfoCache.garbageParam.getCategory().equals(Constant.harm)) {
                //玻璃和有害，免费
                RecyclerInfoCache.garbageParam.setMoney(0.0);
            } else {
                RecyclerInfoCache.garbageParam.setMoney(mWastePrice.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).getCollectorPrice() * RecyclerInfoCache.garbageParam.getQuantity());
            }
            //跳转到确认支付页面
            if (view.getId() != R.id.imBtn_glass && view.getId() != R.id.imBtn_harm) {
                mActivity.getFragmentManager().beginTransaction()
                        .replace(R.id.mid, RecyclerPayFragment.getInstance())
                        .commit();
            } else {
                mActivity.getFragmentManager().beginTransaction()
                        .replace(R.id.mid, RecyclerFreeFragment.getInstance())
                        .commit();
            }
        }
    }

    /**
     * 回收员退出登录
     */
    private void recyclerLogout() {
        //暂停倒计时器
        mActivity.mBackAndTimer.setVisibleState(false).stop();
        //----------测试用-------------//
        //上传回收记录
        ArrayList<RecordBean> records = new ArrayList<>();
        for (String key : RecyclerInfoCache.records.keySet()) {
            if (key.equals(Constant.bottle)) {
                records.add(new RecordBean(Constant.categoryMap.get(key)[3], RecyclerInfoCache.records.get(key).intValue(), 0));
            } else {
                records.add(new RecordBean(Constant.categoryMap.get(key)[3], 0, RecyclerInfoCache.records.get(key)));
            }
        }
        String account = RecyclerInfoCache.telNum;
        Log.i("info", "recyclerSaveRecord_request: " + new Gson().toJson(new SaveRecyclingRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
                account, OrderUtils.getSerialNumber(), records)));
//        OkhttpHelper.postRequest(Constant.baseUrl + "machine/recycling/saveRecord",
//                new Gson().toJson(new SaveRecyclingRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
//                        account, OrderUtils.getSerialNumber(), records)),
//                new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        Log.i("info", "recyclerSaveRecord_onFailure: " + e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        Log.i("info", "recyclerSaveRecord_response" + response.body().string());
//                    }
//                });
        //清空记录
        RecyclerInfoCache.clearRecyclerInfo();
        //跳转到首页
        mActivity.getFragmentManager().beginTransaction()
                .replace(R.id.mid, UserSelectFragment.getInstance())
                .commit();
        TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
